package com.tust.androidbbsclient;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.tust.androidbbsclient.tool.Tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RegisterActivity extends AppCompatActivity {
    private Toast toast;
    private String Uname;

    //用于在线程间传递消息
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);//获取子线程传递的消息
            if (msg.what == 1) {//注册请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("用户注册：" + strMsg);

                switch (strMsg) {
                    case "serverFalse":
                        showToast(Tool.addEmoji() + "服务器通信失败！");
                        break;
                    case "userExist":
                        showToast(Tool.addEmoji() + "用户已存在！");
                        break;
                    case "registerFalse":
                        showToast(Tool.addEmoji() + "注册失败！");
                        break;
                    case "registerSuccess":
                        showToast(Tool.addEmoji() + "注册成功！");

                        //跳转活动
                        Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                        intent.putExtra("Uname", Uname);
                        startActivity(intent);
                        overridePendingTransition(R.anim.fade_out, R.anim.fade_in);//改变跳转活动动画，淡出淡入
                        break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        EditText editTextRegisterUname = this.findViewById(R.id.et_registerUname);
        EditText editTextRegisterUpasswd = this.findViewById(R.id.et_registerUpasswd);
        EditText editTextRegisterConfirmUpasswd = this.findViewById(R.id.et_registerConfirmUpasswd);
        Button buttonRegister = this.findViewById(R.id.btn_register);
        Button buttonRegisterCancel = this.findViewById(R.id.btn_registerCancel);

        //注册按钮监听事件
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uname = editTextRegisterUname.getText().toString();
                String Upasswd = editTextRegisterUpasswd.getText().toString();
                String confirmUpasswd = editTextRegisterConfirmUpasswd.getText().toString();

                //输入值的前端判断
                if (Uname.equals("")) showToast(Tool.addEmoji() + "请输入用户名！");
                else if (Tool.StringLength(Uname) > 20) showToast(Tool.addEmoji() + "用户名小于20字符！");
                else if (Upasswd.equals("")) showToast(Tool.addEmoji() + "请输入密码！");
                else if (confirmUpasswd.equals("")) showToast(Tool.addEmoji() + "请确认密码！");
                else if (Tool.StringLength(Upasswd) > 10 || Tool.StringLength(confirmUpasswd) > 10) showToast(Tool.addEmoji() + "密码小于10字符！");
                else if (!Upasswd.equals(confirmUpasswd)) showToast(Tool.addEmoji() + "密码不一致！");
                else {
                    //发送注册请求子线程
                    new Thread() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            BufferedReader bufferedReader = null;
                            String data = "";
                            try {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 1;//增加handlerMsg标识符

                                java.net.URL url = new URL(Tool.InetAddress + "/userRegister.do");//请求地址
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                                //连接类相关设置
                                connection.setRequestMethod("POST");
                                connection.setConnectTimeout(3000);//连接服务器超时
                                connection.setReadTimeout(3000);//从服务器读取数据超时
                                connection.setDoInput(true);//允许写入，从服务端读取结果流
                                connection.setDoOutput(true);//允许写出，开启Post请求体
                                connection.setUseCaches(false);//不使用Cache
                                connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                                connection.connect();//连接网络
                                String params = "Uname=" + Uname + "&Upasswd=" + Upasswd;//请求体内容
                                outputStream = connection.getOutputStream();//请求输出流
                                outputStream.write(params.getBytes());

                                int code = connection.getResponseCode();//获得响应状态码
                                if (code == 200) {//返回状态码200，连接成功
                                    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                    data = bufferedReader.readLine();

                                    handlerMsg.obj = data;//写入线程传递消息
                                } else  handlerMsg.obj = "serverFalse";//服务器通信失败
                                connection.disconnect();//关闭连接

                                handler.sendMessage(handlerMsg);//发送线程消息
                            } catch (IOException e) {
                                Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                                handlerMsg.what = 1;//增加handlerMsg标识符
                                handlerMsg.obj = "serverFalse";
                                handler.sendMessage(handlerMsg);

                                //throw new RuntimeException(e);
                            } finally {
                                try {
                                    if (bufferedReader != null) bufferedReader.close();
                                    if (outputStream != null) {
                                        outputStream.flush();
                                        outputStream.close();
                                    }
                                } catch (IOException e) {
                                    System.out.println("子线程：finally失败");
                                    //throw new RuntimeException(e);
                                }
                            }
                        }
                    }.start();
                }
            }
        });

        //取消按钮监听事件
        buttonRegisterCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转活动
                Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_out,R.anim.fade_in);//改变跳转活动动画，淡出淡入
            }
        });
    }

    //Toast消息提示框显示方法
    public void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}
